import Taro, { Component } from '@tarojs/taro'
import { View, Text, Swiper, SwiperItem, Map, Image } from '@tarojs/components'
import './index.scss'
import { AtButton, AtFab, AtInput, AtMessage, AtList, AtListItem, AtSearchBar, AtIcon } from 'taro-ui'
import AtTabBar_index from '../../components/AtTabBar_index';
// 引入SDK核心类
import requets from '../../service/api';
import yiyuan_icon from '../../assets/img/yiyuan_icon.png'
// import PublicTemplate from '../../components/PublicTemplate'
var QQMapWX = require('../../assets/qqmap-wx-jssdk1.2/qqmap-wx-jssdk');

var dingwei = require('../../assets/img/dingwei.png')
// 实例化API核心类
var qqmapsdk = new QQMapWX({
  key: 'D43BZ-P7MKO-N4TWG-SGR4H-SLJIE-YAFTN' // 必填
});
var num = 1

export default class Index extends Component {
  config = {
    navigationBarTitleText: '医疗废物收运助手'
  }

  state = {
    AtListData: [],
    downDragStyle2: {
      display: 'none'
    },
    downDragStyle: {
      height: '0vh',
      transition: `all 1s`,
      display: 'none'
    },
    latitude: '',
    longitude: '',
    hospitalName: '',
    markers: [],
    current: 0,//轮播图index
    data: [

    ],
    userId: '',
    scale:16
  }

  componentWillMount() { }

  componentDidMount() {

    this.conditionQueryCollectorObject()

    wx.getLocation({
      type: 'gcj02',
      success: (res) => {
        // console.log(res)
        const latitude = res.latitude
        const longitude = res.longitude
        this.setState({
          latitude, longitude
        }, () => {
          this.getHospitalsByPoint()
        })
      }
    })

    Taro.getStorage({
      key: 'userId',
      success: (res) => {
        this.setState({
          userId: res.data
        }, () => {
          this.getUserLocation()
        })
      }
    })






  }

  getHospitalsByPoint = () => {
    let params = {
      latitude: this.state.latitude,
      longitude: this.state.longitude,
      hospitalName: this.state.hospitalName
    }
    requets.baseOptions({
      url: `/zjn-web/zjn/collector/record/getHospitalsByPoint`,
      method: 'POST',
      data: params
    }).then((res) => {
      if (res.data.rc === 0) {
        if (res.data.ret.length < 1) {
          this.handleClick('warning', '您的周围并无医疗点!')
          return
        }
        const { current } = this.state
        var mks = []
        for (var i = 0; i < res.data.ret.length; i++) {
          mks.push({ // 获取返回结果，放到mks数组中
            title: res.data.ret[i].hospitalName,
            id: i,
            latitude: res.data.ret[i].hosipitolLatitude,
            longitude: res.data.ret[i].hosipitolLongitude,
            iconPath: 'https://zjn.cloudhw.cn/zjn-web/zjn/common/filehandle/showImage?filepath=20200407//20200407215204.png', //图标路径
            width: i == current ? 40 : 20,
            height: i == current ? 40 : 20,
          })
        }
        this.setState({ //设置markers属性，将搜索结果显示在地图中
          markers: mks,
          data: res.data.ret
        })
      }
    })
  }

  getUserLocation = () => {
    let vm = this;
    wx.getSetting({
      success: (res) => {


        if (res.authSetting['scope.userLocationBackground'] != true) {
          wx.showModal({
            title: '请求授权当前位置',
            content: '请设置为使用小程序期间和离开小程序后',
            success: (res) => {
              if (res.cancel) {
                wx.showToast({
                  title: '拒绝授权',
                  icon: 'none',
                  duration: 1000
                })
                this.getUserLocation()
              } else if (res.confirm) {
                wx.openSetting({
                  success: (res) => {
                    // console.log(res, 183)
                    if (res.authSetting["scope.userLocationBackground"] == true) {
                      wx.showToast({
                        title: '授权成功',
                        icon: 'success',
                        duration: 1000
                      })
                      this.getUserLocation()
                    } else {
                      wx.showToast({
                        title: '授权失败',
                        icon: 'none',
                        duration: 1000
                      })
                      this.getUserLocation()
                    }
                  }
                })
              }
            }
          })
        } else {
          wx.startLocationUpdateBackground({
            success: (data) => {

              const _locationChangeFn = res => {

                console.log('location change', res.latitude, res.longitude,res)
                num++;
                if (num % 5 == 0) {
                  requets.baseOptions({
                    url: `/zjn-web/zjn/gps/addToGps?altitude=${res.altitude}&latitude=${res.latitude}&longitude=${res.longitude}&speed=${res.speed}&userId=${this.state.userId}`,
                    method: 'GET',
                    data: {}
                  }).then((res) => {

                  })
                }
              }
              wx.onLocationChange(_locationChangeFn);
            }
          })
        }


      }
    })
  }
  handleClick = (type, text) => {
    Taro.atMessage({
      'message': text,
      'type': type,
    })
  }

  componentWillUnmount() { }

  componentDidShow() { }

  componentDidHide() { }


  chongxinXuanRan = () => {
    const { data, current } = this.state
    var mks = []
    for (var i = 0; i < data.length; i++) {
      mks.push({ // 获取返回结果，放到mks数组中
        title: data[i].hospitalName,
        id: i,
        latitude: data[i].hosipitolLatitude,
        longitude: data[i].hosipitolLongitude,
        iconPath: 'https://zjn.cloudhw.cn/zjn-web/zjn/common/filehandle/showImage?filepath=20200407//20200407215204.png', //图标路径
        width: i == current ? 40 : 20,
        height: i == current ? 40 : 20,
      })
    }

    this.setState({ //设置markers属性，将搜索结果显示在地图中
      markers: mks
    })
  }



  onChangeSwiper = (v) => {
    // console.log(this.state.data)
    this.setState({
      current: v.target.current,
      latitude: this.state.data[v.target.current].hosipitolLatitude,
      longitude: this.state.data[v.target.current].hosipitolLongitude,
    }, () => {
      this.chongxinXuanRan()
    })
  }

  bindmarkertap = (e, v) => {
    // console.log(e.markerId)
    this.setState({
      current: e.markerId
    }, () => {
      this.chongxinXuanRan()
    })
  }



  onDingwei = () => {
    wx.getLocation({
      type: 'gcj02',
      success: (res) => {
        // console.log(res)
        const latitude = res.latitude
        const longitude = res.longitude
        this.setState({
          latitude, longitude,
          scale:16
        }, () => {
          this.getHospitalsByPoint()
        })
      }
    })
  }

  handleChange = (v) => {
    this.setState({
      hospitalName: v
    })
  }

  onFocus = () => {
    this.setState({
      downDragStyle: {
        height: '60vh',
        transition: `all 1s`,
        display: ''
      },
      downDragStyle2: {
        display: ''
      }
    })
  }

  onShouqi = () => {
    this.setState({
      downDragStyle: {
        height: '0vh',
        transition: `all 1s`,
        display: 'none'
      },
      downDragStyle2: {
        display: 'none'
      }
    })
  }

  onActionClick = () => {
    this.getHospitalsByPoint()
    this.conditionQueryCollectorObject()
  }

  conditionQueryCollectorObject = () => {
    requets.baseOptions({
      url: `/zjn-web/zjn/collector/object/conditionQueryCollectorObject`,
      method: 'POST',
      data: {hospitalName:this.state.hospitalName}
    }).then((res) => {
      if (res.data.rc === 0) {
        this.setState({
          AtListData: res.data.ret
        })
      }
    })
  }


  onAtListItem = (item) => {
    Taro.navigateTo({
      url: `/pages/details/index?hospitalId=${item.hospitalId}&hospitalName=${item.hospitalName}&hospitalAddress=${item.hospitalAddress}&pages=收集上报&next=index`
    })
  }

  onAdd = () => {
    if(this.state.scale > 19){
      this.handleClick('','已经放大到最大了!')
      return
    }
    let scale = this.state.scale + 1
    this.setState({
      scale
    })
  }

  onRemove = () => {
    if(this.state.scale < 4){
      this.handleClick('','已经缩小到最小了!')
      return
    }
    let scale = this.state.scale - 1
    this.setState({
      scale
    })
  }

  stringToEllipsis = (text, lens) => {
    let textCopy = text;
    let len = lens ? lens : 10;
    text = text ? (text.length > len ? text.substr(0, len - 1) + '...' : text) : '';
    return  text
      
    
  }



  render() {

    const { markers, longitude, latitude, data, current, downDragStyle, AtListData, downDragStyle2 } = this.state
    return (
      <View className='index'>
        <AtTabBar_index current={0} />
        <AtMessage />
        <View className='dingwei_Tbox' >
          <AtIcon value='add' size='24' color='#333' onClick={this.onAdd}></AtIcon>
          <AtIcon value='subtract' size='24' color='#333' onClick={this.onRemove}></AtIcon>
        </View>

        <View className='dingwei_box' onClick={this.onDingwei}>
          <Image src={dingwei} className='dingwei' />
        </View>
        <View className='liebiao' style={downDragStyle}>
          <AtList>
            <View style={{ height: '7vh' }}></View>
            {
              AtListData.map((item, index) => {
                return (
                  <AtListItem
                    key={index}
                    arrow='right'
                    note={item.hospitalAddress}
                    title={item.hospitalName}
                    onClick={this.onAtListItem.bind(this, item)}
                  />
                )
              })
            }

          </AtList>

        </View>
        <View className='shouqi' onClick={this.onShouqi} style={downDragStyle2}><AtIcon value='chevron-up' size='30' color='#ccc'></AtIcon></View>
        <View className='sousuo'>

          <AtSearchBar
            onFocus={this.onFocus}
            onBlur={this.onBlur}
            // showActionButton
            value={this.state.hospitalName}
            onChange={this.handleChange.bind(this)}
            onActionClick={this.onActionClick.bind(this)}
          />
        </View>

        <View className='map_box'>
          <Map id="myMap"

            subkey='D43BZ-P7MKO-N4TWG-SGR4H-SLJIE-YAFTN'
            markers={markers}
            show-scale={true}
            show-compass={true}
            show-location={true}
            style="width:100%;height:100%;"
            longitude={longitude}
            latitude={latitude}
            onMarkerTap={this.bindmarkertap}
            onPoiTap={this.bindmarkertap}
            scale={this.state.scale}>

          </Map >
        </View>
        <View className='Swiper_box'>
          <Swiper
            className='Swiper_boxtest'
            indicatorColor='#999'
            indicatorActiveColor='#333'
            vertical={false}
            circular
            current={current}
            onChange={this.onChangeSwiper}
            indicatorDots={true}
          // autoplay
          >
            {
              data.map((item, index) => {
                return (
                  <SwiperItem key={index} >
                    <View className='Swiper_boxtest_box'>
                      <View className='Swiper_boxtest_box_left'>
                        <View className='Swiper_boxtest_box_left_top'>{item.hospitalName}</View>
                        <View className='Swiper_boxtest_box_left_bottom'>{item.distance}m | {this.stringToEllipsis(item.hospitalAddress,10)}</View>
                      </View>
                      <View className='Swiper_boxtest_box_right'><AtButton type='primary' size='small' onClick={this.onAtListItem.bind(this, item)}>下一步</AtButton></View>
                    </View>
                  </SwiperItem>
                )
              })
            }


          </Swiper>

        </View>
        <View style={{ height: '8vh' }}></View>
      </View>
    )
  }
}
